#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
统计数据路由
提供仪表板所需的各类统计数据
"""

from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from models import db, Problem, Submission, User, Course, Class, Assignment, AssignmentSubmission, SystemLog
from datetime import datetime, timedelta
import psutil
import os
from sqlalchemy import func, and_

statistics_bp = Blueprint('statistics', __name__)

def get_online_users():
    """获取在线用户数（基于最近5分钟有活动的用户）"""
    try:
        five_minutes_ago = datetime.now() - timedelta(minutes=5)
        online_users = User.query.filter(
            User.last_activity >= five_minutes_ago
        ).count()
        return online_users
    except Exception as e:
        # 如果出错，返回活跃用户总数
        return User.query.filter(User.status == 'active').count()

def get_system_status():
    """获取系统状态"""
    try:
        # CPU使用率
        cpu_percent = psutil.cpu_percent(interval=1)
        
        # 内存使用率
        memory = psutil.virtual_memory()
        memory_percent = memory.percent
        
        # 系统运行时间
        uptime = datetime.now() - datetime.fromtimestamp(psutil.boot_time())
        uptime_hours = int(uptime.total_seconds() / 3600)
        
        # 系统状态
        status = "正常"
        if cpu_percent > 80 or memory_percent > 80:
            status = "警告"
        if cpu_percent > 95 or memory_percent > 95:
            status = "危险"
            
        return {
            "status": status,
            "uptime": uptime_hours,
            "memory": memory_percent,
            "cpu": cpu_percent
        }
    except Exception as e:
        return {
            "status": "未知",
            "uptime": 0,
            "memory": 0,
            "cpu": 0
        }

@statistics_bp.route('/dashboard', methods=['GET'])
@jwt_required()
def get_dashboard_stats():
    """获取仪表板统计数据"""
    try:
        # 基础统计数据
        total_problems = Problem.query.count()
        total_submissions = Submission.query.count()
        total_users = User.query.count()
        total_courses = Course.query.count()
        total_classes = Class.query.count()
        total_assignments = Assignment.query.count()
        
        # 通过率计算
        successful_submissions = Submission.query.filter(
            Submission.status == 'accepted'
        ).count()
        success_rate = round((successful_submissions / total_submissions * 100) if total_submissions > 0 else 0, 1)
        
        # 在线用户数
        online_users = get_online_users()
        
        # 最近提交数（24小时内）
        yesterday = datetime.now() - timedelta(days=1)
        recent_submissions = Submission.query.filter(
            Submission.submit_time >= yesterday
        ).count()
        
        # 待批改提交数
        pending_submissions = Submission.query.filter(
            Submission.status.in_(['pending', 'running'])
        ).count()
        
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': {
                'totalProblems': total_problems,
                'totalSubmissions': total_submissions,
                'totalUsers': total_users,
                'totalCourses': total_courses,
                'totalClasses': total_classes,
                'totalAssignments': total_assignments,
                'successRate': success_rate,
                'onlineUsers': online_users,
                'recentSubmissions': recent_submissions,
                'pendingSubmissions': pending_submissions
            }
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@statistics_bp.route('/user', methods=['GET'])
@jwt_required()
def get_user_stats():
    """获取用户个人统计数据"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user:
            return jsonify({'error': '用户不存在'}), 404
            
        # 我的提交数
        my_submissions = Submission.query.filter(
            Submission.student_id == current_user_id
        ).count()
        
        # 已完成作业数
        completed_assignments = Submission.query.filter(
            and_(
                Submission.student_id == current_user_id,
                Submission.status == 'accepted'
            )
        ).count()
        
        # 待完成作业数（简化处理）
        pending_assignments = Assignment.query.filter(
            Assignment.due_date > datetime.now()
        ).count() - completed_assignments
        
        # 我的通过率
        successful_submissions = Submission.query.filter(
            and_(
                Submission.student_id == current_user_id,
                Submission.status == 'accepted'
            )
        ).count()
        my_success_rate = round((successful_submissions / my_submissions * 100) if my_submissions > 0 else 0, 1)
        
        # 我的课程数（学生端）
        my_courses = 0
        my_classes = 0
        if user.role == 'student':
            # 这里需要根据实际的课程和班级关联关系来查询
            # 暂时返回模拟数据
            my_courses = 3
            my_classes = 2
        
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': {
                'mySubmissions': my_submissions,
                'completedAssignments': completed_assignments,
                'pendingAssignments': max(0, pending_assignments),
                'mySuccessRate': my_success_rate,
                'myCourses': my_courses,
                'myClasses': my_classes
            }
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@statistics_bp.route('/teacher', methods=['GET'])
@jwt_required()
def get_teacher_stats():
    """获取教师统计数据"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role != 'teacher':
            return jsonify({'error': '权限不足'}), 403
            
        # 获取教师创建的课程
        my_courses = Course.query.filter(
            Course.teacher_id == current_user_id
        ).count()
        
        # 获取教师创建的题目
        my_problems = Problem.query.filter(
            Problem.created_by == current_user_id
        ).count()
        
        # 获取教师班级的学生提交数
        my_classes = Class.query.filter(
            Class.teacher_id == current_user_id
        ).all()
        
        pending_submissions = 0
        student_count = 0
        
        for class_obj in my_classes:
            # 统计班级学生数
            student_count += len(class_obj.students)
            
            # 统计待批改提交数
            class_assignments = Assignment.query.filter(
                Assignment.class_id == class_obj.id
            ).all()
            
            for assignment in class_assignments:
                pending_submissions += AssignmentSubmission.query.filter(
                    AssignmentSubmission.assignment_id == assignment.id,
                    AssignmentSubmission.status.in_(['pending', 'running'])
                ).count()
        
        # 获取教师的作业数
        my_assignments = Assignment.query.filter(
            Assignment.class_id.in_([c.id for c in my_classes])
        ).count()
        
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': {
                'myCourses': my_courses,
                'myProblems': my_problems,
                'pendingSubmissions': pending_submissions,
                'studentCount': student_count,
                'myAssignments': my_assignments,
                'myClasses': len(my_classes)
            }
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@statistics_bp.route('/student', methods=['GET'])
@jwt_required()
def get_student_stats():
    """获取学生统计数据"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role != 'student':
            return jsonify({'error': '权限不足'}), 403
            
        # 获取学生的提交统计
        total_submissions = Submission.query.filter(
            Submission.student_id == current_user_id
        ).count()
        
        successful_submissions = Submission.query.filter(
            Submission.student_id == current_user_id,
            Submission.status == 'accepted'
        ).count()
        
        # 计算通过率
        success_rate = round((successful_submissions / total_submissions * 100) if total_submissions > 0 else 0, 1)
        
        # 获取学生解决的题目数
        solved_problems = db.session.query(func.count(func.distinct(Submission.problem_id))).filter(
            Submission.student_id == current_user_id,
            Submission.status == 'accepted'
        ).scalar()
        
        # 获取学生的作业数
        my_assignments = Assignment.query.join(Class).filter(
            Class.students.any(id=current_user_id)
        ).count()
        
        # 获取学生的课程数
        my_courses = Course.query.join(Class).filter(
            Class.students.any(id=current_user_id)
        ).count()
        
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': {
                'totalSubmissions': total_submissions,
                'successfulSubmissions': successful_submissions,
                'successRate': success_rate,
                'solvedProblems': solved_problems,
                'myAssignments': my_assignments,
                'myCourses': my_courses
            }
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@statistics_bp.route('/admin', methods=['GET'])
@jwt_required()
def get_admin_stats():
    """获取管理员统计数据"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role != 'admin':
            return jsonify({'error': '权限不足'}), 403
            
        # 系统总览数据
        total_problems = Problem.query.count()
        total_submissions = Submission.query.count()
        total_users = User.query.count()
        total_courses = Course.query.count()
        total_classes = Class.query.count()
        total_assignments = Assignment.query.count()
        
        # 通过率
        successful_submissions = Submission.query.filter(
            Submission.status == 'accepted'
        ).count()
        success_rate = round((successful_submissions / total_submissions * 100) if total_submissions > 0 else 0, 1)
        
        # 在线用户数
        online_users = get_online_users()
        
        # 系统状态
        system_status = get_system_status()
        
        # 最近活动数（24小时内）
        yesterday = datetime.now() - timedelta(days=1)
        recent_activities = SystemLog.query.filter(
            SystemLog.created_at >= yesterday
        ).count()
        
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': {
                'totalProblems': total_problems,
                'totalSubmissions': total_submissions,
                'totalUsers': total_users,
                'totalCourses': total_courses,
                'totalClasses': total_classes,
                'totalAssignments': total_assignments,
                'successRate': success_rate,
                'onlineUsers': online_users,
                'systemStatus': system_status['status'],
                'recentActivities': recent_activities
            }
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@statistics_bp.route('/students', methods=['GET'])
@jwt_required()
def get_students_stats():
    """获取学生统计数据"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role not in ['admin', 'teacher']:
            return jsonify({'error': '权限不足'}), 403
            
        # 学生总数
        total_students = User.query.filter(User.role == 'student').count()
        
        # 活跃学生数
        active_students = User.query.filter(
            User.role == 'student',
            User.status == 'active'
        ).count()
        
        # 停用学生数
        suspended_students = User.query.filter(
            User.role == 'student',
            User.status == 'suspended'
        ).count()
        
        # 毕业学生数
        graduated_students = User.query.filter(
            User.role == 'student',
            User.status == 'graduated'
        ).count()
        
        # 计算平均分数（基于提交记录）
        avg_score_result = db.session.query(func.avg(Submission.score)).filter(
            Submission.status == 'accepted'
        ).scalar()
        average_score = round(avg_score_result if avg_score_result else 0, 1)
        
        # 总解题数
        total_problems_solved = db.session.query(func.count(func.distinct(
            db.session.query(Submission.problem_id, Submission.student_id)
        ))).filter(
            Submission.status == 'accepted'
        ).scalar()
        
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': {
                'total_students': total_students,
                'active_students': active_students,
                'suspended_students': suspended_students,
                'graduated_students': graduated_students,
                'average_score': average_score,
                'total_problems_solved': total_problems_solved or 0
            }
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@statistics_bp.route('/online-users', methods=['GET'])
@jwt_required()
def get_online_users_count():
    """获取在线用户数"""
    try:
        online_users = get_online_users()
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': {'onlineUsers': online_users}
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@statistics_bp.route('/system-status', methods=['GET'])
@jwt_required()
def get_system_status_route():
    """获取系统状态"""
    try:
        system_status = get_system_status()
        return jsonify({
            'code': 200,
            'message': '获取成功',
            'data': system_status
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500
